const app = getApp()
const DRAFT_KEY = 'cookingDraft'

Page({
  data: {
    formData: {
      title: '',
      timeRange: ['', ''],
      ingredients: [],
      images: []
    },
    errors: {},
    showTimePicker: false,
    timePickerType: 'start',
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    maxDate: new Date().getTime() + 24 * 60 * 60 * 1000,
    submitting: false,
    uploading: false,
    draftTimer: null
  },

  onLoad() {
    // 设置默认时间范围(18:00-19:00)
    const today = new Date()
    today.setHours(18, 0, 0, 0)
    const endTime = new Date(today.getTime() + 60 * 60 * 1000)
    
    this.setData({
      'formData.timeRange': [
        this.formatTime(today),
        this.formatTime(endTime)
      ]
    })

    // 恢复草稿
    this.restoreDraft()
    
    // 启动自动保存
    this.startAutoDraft()
  },

  onUnload() {
    // 清除定时器
    if (this.data.draftTimer) {
      clearInterval(this.data.draftTimer)
    }
  },

  // 自动保存草稿
  startAutoDraft() {
    const timer = setInterval(() => {
      this.saveDraft()
    }, 30000) // 每30秒保存一次
    this.setData({ draftTimer: timer })
  },

  saveDraft() {
    try {
      wx.setStorageSync(DRAFT_KEY, this.data.formData)
    } catch (err) {
      console.error('保存草稿失败', err)
    }
  },

  restoreDraft() {
    try {
      const draft = wx.getStorageSync(DRAFT_KEY)
      if (draft) {
        this.setData({ formData: draft })
      }
    } catch (err) {
      console.error('恢复草稿失败', err)
    }
  },

  // 菜品名称变化
  onTitleChange(e) {
    this.setData({
      'formData.title': e.detail,
      'errors.title': ''
    })
  },

  // 显示时间选择器
  showStartTimePicker() {
    this.setData({
      showTimePicker: true,
      timePickerType: 'start',
      currentDate: this.data.formData.timeRange[0] ? 
        new Date(this.data.formData.timeRange[0]).getTime() : 
        new Date().getTime()
    })
  },

  showEndTimePicker() {
    this.setData({
      showTimePicker: true,
      timePickerType: 'end',
      currentDate: this.data.formData.timeRange[1] ? 
        new Date(this.data.formData.timeRange[1]).getTime() : 
        new Date().getTime()
    })
  },

  onTimePickerClose() {
    this.setData({ showTimePicker: false })
  },

  // 时间选择确认
  onTimeConfirm(e) {
    const { timePickerType, formData } = this.data
    const timeStr = this.formatTime(new Date(e.detail))
    const timeRange = [...formData.timeRange]

    if (timePickerType === 'start') {
      timeRange[0] = timeStr
    } else {
      timeRange[1] = timeStr
    }

    this.setData({
      'formData.timeRange': timeRange,
      showTimePicker: false
    })
  },

  // 添加食材
  addIngredient() {
    const ingredients = [...this.data.formData.ingredients, { name: '', amount: '' }]
    this.setData({
      'formData.ingredients': ingredients
    })
  },

  // 删除食材
  removeIngredient(e) {
    const { index } = e.currentTarget.dataset
    const ingredients = [...this.data.formData.ingredients]
    ingredients.splice(index, 1)
    this.setData({
      'formData.ingredients': ingredients
    })
  },

  // 食材信息变化
  onIngredientChange(e) {
    const { index, type } = e.currentTarget.dataset
    const ingredients = [...this.data.formData.ingredients]
    ingredients[index][type] = e.detail
    this.setData({
      'formData.ingredients': ingredients
    })
  },

  // 上传图片
  async afterRead() {
    if (this.data.uploading) return
    
    wx.showLoading({ title: '上传中...' })
    this.setData({ uploading: true })
    
    try {
      // 检查云开发是否初始化
      if (!wx.cloud) {
        throw new Error('请使用 2.2.3 或以上的基础库以使用云能力')
      }

      // 选择图片
      const { tempFiles } = await wx.chooseMedia({
        count: 9 - this.data.formData.images.length,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['compressed'],
        camera: 'back',
      })

      if (!tempFiles || !tempFiles.length) {
        throw new Error('未选择任何图片')
      }

      // 添加临时图片到列表
      const newImages = tempFiles.map(file => ({
        thumb: file.tempFilePath,
        progress: 0
      }))
      
      const currentLength = this.data.formData.images.length
      this.setData({
        'formData.images': [...this.data.formData.images, ...newImages]
      })

      // 处理每个文件
      const uploadTasks = tempFiles.map(async (file, index) => {
        try {
          const ext = file.tempFilePath.split('.').pop()
          const cloudPath = `cooking/${Date.now()}-${Math.random().toString(36).slice(-6)}.${ext}`

          // 上传到云存储
          return new Promise((resolve, reject) => {
            const uploadTask = wx.cloud.uploadFile({
              cloudPath,
              filePath: file.tempFilePath,
              success: res => {
                if (!res.fileID) {
                  reject(new Error('上传失败：未获取到文件ID'))
                  return
                }
                resolve({
                  url: res.fileID,
                  type: 'image',
                  thumb: res.fileID,
                  progress: 100
                })
              },
              fail: err => {
                reject(new Error(err.errMsg || '上传失败'))
              }
            })
            
            // 监听上传进度
            uploadTask.onProgressUpdate(res => {
              const key = `formData.images[${currentLength + index}].progress`
              this.setData({
                [key]: res.progress
              })
            })
          })
        } catch (err) {
          const errMsg = err.message || err.errMsg || '未知错误'
          console.error('处理单个文件失败:', errMsg)
          throw new Error(`上传失败: ${errMsg}`)
        }
      })

      const uploadedFiles = await Promise.all(uploadTasks)

      // 更新图片列表
      this.setData({
        'formData.images': [
          ...this.data.formData.images.slice(0, currentLength),
          ...uploadedFiles
        ]
      })

      wx.showToast({
        title: '上传成功',
        icon: 'success'
      })

    } catch (err) {
      console.error('上传图片失败:', err)
      wx.showToast({
        title: err.message || '上传失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
      this.setData({ uploading: false })
    }
  },

  // 压缩图片
  async compressImage(filePath) {
    try {
      // 获取图片信息
      const { width, height } = await wx.getImageInfo({
        src: filePath
      })
      
      // 只有大图才压缩
      if (width > 1024 || height > 1024) {
        const { tempFilePath } = await wx.compressImage({
          src: filePath,
          quality: 80,
          compressedWidth: Math.min(width, 1024) // 保持宽高比
        })
        return tempFilePath
      }
      return filePath
    } catch (err) {
      console.error('压缩图片失败', err)
      return filePath
    }
  },

  // 删除图片
  onDelete(e) {
    const { index } = e.currentTarget.dataset
    const images = [...this.data.formData.images]
    const deletedImage = images.splice(index, 1)[0]

    // 从云存储中删除
    if (deletedImage && deletedImage.url) {
      wx.cloud.deleteFile({
        fileList: [deletedImage.url]
      }).catch(err => {
        console.error('删除云存储文件失败', err)
      })
    }

    this.setData({
      'formData.images': images
    })
  },

  // 格式化时间
  formatTime(date) {
    date = new Date(date)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 表单验证
  validateForm() {
    const { formData } = this.data
    const errors = {}

    if (!formData.title.trim()) {
      errors.title = '请输入菜品名称'
    }

    if (!formData.timeRange[0] || !formData.timeRange[1]) {
      wx.showToast({
        title: '请选择烹饪时间',
        icon: 'none'
      })
      return false
    }

    const startTime = new Date(formData.timeRange[0]).getTime()
    const endTime = new Date(formData.timeRange[1]).getTime()
    
    if (endTime <= startTime) {
      wx.showToast({
        title: '结束时间必须晚于开始时间',
        icon: 'none'
      })
      return false
    }

    if (endTime - startTime > 24 * 60 * 60 * 1000) {
      wx.showToast({
        title: '烹饪时间不能超过24小时',
        icon: 'none'
      })
      return false
    }

    this.setData({ errors })
    return Object.keys(errors).length === 0
  },

  // 提交表单
  async onSubmit() {
    if (!this.validateForm()) return

    this.setData({ submitting: true })

    try {
      const { result } = await wx.cloud.callFunction({
        name: 'saveCookingRecord',
        data: {
          ...this.data.formData,
          createTime: new Date()
        }
      })

      if (result.success) {
        // 清除草稿
        wx.removeStorageSync(DRAFT_KEY)
        
        wx.showToast({
          title: '发布成功',
          icon: 'success'
        })

        // 返回列表页并刷新
        setTimeout(() => {
          const pages = getCurrentPages()
          const listPage = pages.find(p => p.route === 'pages/cooking-list/cooking-list')
          
          if (listPage) {
            // 如果列表页存在,返回并刷新
            listPage.setData({
              records: [],
              hasMore: true
            })
            listPage.loadRecords()
            wx.navigateBack()
          } else {
            // 如果列表页不存在,重定向到列表页
            wx.redirectTo({
              url: '/pages/cooking-list/cooking-list'
            })
          }
        }, 1500)
      } else {
        throw new Error(result.error)
      }
    } catch (err) {
      console.error('提交失败', err)
      
      // 离线存储
      try {
        const offlineData = wx.getStorageSync('offlineCooking') || []
        offlineData.push({
          ...this.data.formData,
          createTime: new Date(),
          pending: true
        })
        wx.setStorageSync('offlineCooking', offlineData)
        
        wx.showToast({
          title: '已保存至草稿',
          icon: 'success'
        })
      } catch (storageErr) {
        wx.showToast({
          title: '保存失败',
          icon: 'error'
        })
      }
    } finally {
      this.setData({ submitting: false })
    }
  },

  // 文件大小限制处理
  onOversize(e) {
    wx.showToast({
      title: '图片大小不能超过10M',
      icon: 'none'
    })
  },

  // 上传前校验
  beforeRead(e) {
    const { callback, file } = e.detail
    
    // 检查文件类型
    if (!/\.(jpg|jpeg|png|gif)$/i.test(file.url)) {
      wx.showToast({
        title: '只能上传图片文件',
        icon: 'none'
      })
      callback(false)
      return
    }

    callback(true)
  }
}) 